//
//  YLLTimer.swift
//  yilule
//
//  Created by lidi on 16/5/18.
//  Copyright © 2016年 topview. All rights reserved.
//

import Foundation

class YLLTimer : NSObject {
    
    private var timer:DispatchSourceTimer?
    private var repeatCount:Int?
    private var time:Double
    private var handle:(()->Void)?
    private var handleWithSteper:((_ steper:Int)->Void)?
    private var complete:(()->Void)?

    init(time:Double) {
        self.time = time
    }
    
    init(time:Double,repeatCount:Int) {
        self.time = time
        self.repeatCount = repeatCount
    }
    
    func handle(_ compute:(()->Void)?) -> YLLTimer {
        self.handle = compute
        return self
    }
    
    func complete(_ complete:(()->Void)?) -> YLLTimer {
        self.complete = complete
        return self
    }
    
    func handleWithSteper(_ handleWithSteper:((_ steper:Int)->Void)?) -> YLLTimer {
        self.handleWithSteper = handleWithSteper
        return self
    }
    
    /**
     开始计时
     
     - returns: self
     */
    func resume(_ delay:TimeInterval = 0) -> YLLTimer {
        let queue = DispatchQueue.global(qos: .default)
        timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
        let milliseconds = Int(time * 1000)
        timer?.schedule(deadline: .now() + delay, repeating: .milliseconds(milliseconds))
        timer?.setEventHandler(handler: { [weak self] in
            DispatchQueue.main.async {
                if let repeatCount_ = self?.repeatCount {
                    if repeatCount_ < 0 {
                        _ = self?.stop()
                        self?.complete?()
                        return
                    }
                    else {
                        self?.handleWithSteper?(repeatCount_)
                    }
                    
                    self?.repeatCount = repeatCount_ - 1
                }
                
                self?.handle?()
            }

        })
        timer?.resume()
  
        return self
    }
    
    /**
     停止计时
     
     - returns: self
     */
    func stop() -> YLLTimer {
        
        if let timer_ = self.timer {
            timer_.cancel()
            self.timer = nil
        }
        
        return self
    }
    
}
